namespace Ray.Web.Controllers
{
	using Castle.MonoRail.Framework;
    using System;
    using Ray.Web.Models;

    [Layout("Register")]
	public class LoginController : BaseController
	{
        //, ControllerDetails(Area="admin")
		public void Index()
		{
		}

		[AccessibleThrough(Verb.Post)]
		public void Authenticate(string username, string password, bool autoLogin)
		{
			// In a real situation, you would like to authenticate the user here. 
			// As a matter of example, we're just getting the parameters sent 
			// and displaying it back to the user
			PropertyBag["username"] = username;
			PropertyBag["password"] = password;
			PropertyBag["autoLogin"] = autoLogin;

            //RedirectToAction("index");
		}
        public void Login(String username, String password, bool rememberme, string ReturnUrl)
        {
            // We should authenticate against a database table or something similar
            // but here, everything is ok as long as the 
            // password and username are non-empty

            if (IsValid(username, password))
            {
                CancelView();

                // Ideally we would look up an user from the database
                // The domain model that represents the user
                // could implement IPrincipal or we could use an adapter

                //User user = new User(username, new string[0]);
                Ray_Master ray_Master = Ray_Master.FindByMasterName(username);
                ray_Master.SetAuthenticated();

                PropertyBag["username"] = username;
                PropertyBag["password"] = password;
                Session["Ray_Master"] = ray_Master;
                RenderView("Success");
                //Redirect(ReturnUrl);
                //Session["user"] = user;
                //RedirectToAction("Login");
                //Redirect(ReturnUrl);
            }
            else
            {
                // If we got here then something is wrong 
                // with the supplied username/password

                Flash["error"] = "Invalid user name or password. Try again.";
                RedirectToAction("Index", "ReturnUrl=" + ReturnUrl);
            }
        }
        private static bool IsValid(string username, string password)
        {

            return Ray_Master.ValidateUser(username,password);
        }
	}
}
